﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using App.Core.Extensions;
using App.Data;
using System.IO;

public partial class Pages_Admin_MediaReportChange : BasePage
{
    private int _ID = 0;
    private bool _IsEditMode = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        if (!IsPostBack)
        {
            BindDropDownLists();
            BindTestimonialInfo();
            ShowSuccessMessage();
        }
    }
    /// <summary>
    /// Bindis the Page Initialization Variables
    /// </summary>
    protected void BindPageInfo()
    {
        _ID = WebUtil.GetQueryStringInInt(AppConstants.QueryString.ID);
        if (_ID > 0)
        {
            _IsEditMode = true;
            h4Heading.InnerHtml = "Edit Media Report";
        }
        Page.Title = WebUtil.GetPageTitle(h4Heading.InnerHtml);
    }
    protected void ShowSuccessMessage()
    {
        if (String.Compare(WebUtil.GetQueryStringInString(AppConstants.QueryString.SUCCESS_MESSAGE), "True", false) == 0)
        {
            WebUtil.ShowMessageBox(divMessage, "Media Report Saved Successfully.", false);
        }
    }
    /// <summary>
    /// Binds Dropdownlists for the initial request.
    /// </summary>
    protected void BindDropDownLists()
    {
        //BindDropdownList.Users(ddlModifiedBy);
    }
    /// <summary>
    /// Binds Testimonial Info Requested through Query Strings
    /// </summary>
    protected void BindTestimonialInfo()
    {
        if (_IsEditMode)
        {
            BtcHousingEntities context = new BtcHousingEntities();
            MediaReport entity = context.MediaReports.FirstOrDefault(P => P.ID == _ID);//dao.GetByID(_ID);
            if (entity == null)
                ShowErrorMessage();
            else
            {
                txtTitle.Text = entity.Title;
                txtDescription.Text = entity.Description;
                //txtImage.Text = entity.Image;
                String imageHTML = String.Format("<img class='AdverstisementImage' src='{0}/{1}' alt='' title='' /><br /> <a href='{0}/{2}' target='_blank'>{3}</a>",
                    AppConstants.MEDIA_REPORT_FILES
                    , entity.ThumbImage
                    , entity.Image
                    , WebUtil.GetFormattedFileName(entity.Image));
                divAddPreviewContainer.InnerHtml = imageHTML;
                divAddPreviewContainer.Visible = true;
                txtReceiveDate.Text = entity.ReceiveDate.ToString(ConfigReader.CSharpCalendarDateFormat);
                rfvFileName.Enabled = false;
                chkHasPublished.Checked = entity.HasPublished;
            }
        }
    }
    /// <summary>
    /// Shows a Message in the UI and Hides the Data Editing Controls
    /// </summary>
    protected void ShowErrorMessage()
    {
        pnlFormContainer.Visible = false;
        WebUtil.ShowMessageBox(divMessage, "Requested Testimonial was not found.", true);
    }
    protected void SaveTestimonial()
    {
        BtcHousingEntities context = new BtcHousingEntities();
        MediaReport entity = null;

        if (_IsEditMode)
            entity = context.MediaReports.FirstOrDefault(P => P.ID == _ID); //dao.GetByID(_ID);        
        else
        {
            entity = new MediaReport();
            entity.Created = DateTime.Now;
            context.AddToMediaReports(entity);
            entity.Image = "NA"; ///For Initial Insert. Will be replaced by the Image File name later.
        }

        entity.Title = txtTitle.Text;
        entity.Description = txtDescription.Text;
        if (_IsEditMode && fuImage.HasFile)
            SaveMediaReportImage(entity);

        entity.ReceiveDate = txtReceiveDate.Text.ToDateTime(ConfigReader.CSharpCalendarDateFormat);
        entity.HasPublished = chkHasPublished.Checked;
        entity.Modified = DateTime.Now;
        entity.ModifiedBy = SessionCache.CurrentUser.ID;

        context.SaveChanges();

        if (!_IsEditMode)
        {
            SaveMediaReportImage(entity);
            context.SaveChanges();
        }
        //WebUtil.ShowMessageBox(divMessage, "Testimonial Saved Successfully.", false);
        String url = String.Format("{0}?{1}=True", Request.Url.AbsolutePath, AppConstants.QueryString.SUCCESS_MESSAGE);
        Response.Redirect(url);
    }
    private void SaveMediaReportImage(MediaReport entity)
    {
        String fileDirectory = Server.MapPath(AppConstants.MEDIA_REPORT_FILES);
        if (_IsEditMode)
        {
            ///Delete Existing File
            if (!entity.Image.IsNullOrEmpty())
            {
                String filePath = Path.Combine(fileDirectory, entity.Image);
                if (File.Exists(filePath))
                    File.Delete(filePath);
            }
            if (!entity.ThumbImage.IsNullOrEmpty())
            {
                String filePath = Path.Combine(fileDirectory, entity.ThumbImage);
                if (File.Exists(filePath))
                    File.Delete(filePath);
            }
        }
        if (!Directory.Exists(fileDirectory))
            Directory.CreateDirectory(fileDirectory);

        String outputFileName = Path.Combine(fileDirectory, String.Format("{0}_{1}_Thumb{2}", entity.ID, Path.GetFileNameWithoutExtension(fuImage.PostedFile.FileName), Path.GetExtension(fuImage.PostedFile.FileName)));
        String inputFileName = Path.Combine(fileDirectory, String.Format("{0}_{1}", entity.ID, Path.GetFileName(fuImage.PostedFile.FileName)));
        fuImage.SaveAs(inputFileName);
        WebUtil.GenerateThumbnail(inputFileName, outputFileName, ConfigReader.MediaReportThumbWidth, false);
        
        ///Set File Names
        entity.Image = Path.GetFileName(inputFileName);
        entity.ThumbImage = Path.GetFileName(outputFileName);
        
        //return Path.GetFileName(outputFileName);
    }
    #region Event handlers
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            SaveTestimonial();
            //Response.Redirect(AppConstants.Pages.TESTIMONIAL_LIST);
            return;
        }
    }
    protected void btnList_Click(object sender, EventArgs e)
    {
        //Response.Redirect(AppConstants.Pages.TESTIMONIAL_LIST);
        return;
    }
    protected void cvFileName_OnServerValidate(object sender, ServerValidateEventArgs e)
    {        
        e.IsValid = _IsEditMode ? true : false;
        if (fuImage.HasFile)
        {
            if (WebUtil.IsValidImageFile(fuImage.PostedFile))
                e.IsValid = true;            
        }        
    }
    #endregion Event Handlers
}